package com.drinks.yiniang.ui.activity.common;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.drinks.yiniang.R;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.io.api.CommonApiIO;
import com.drinks.yiniang.io.api.InvoiceApiIO;
import com.drinks.yiniang.io.api.UserApiIO;
import com.drinks.yiniang.io.http.HttpUrls;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.utils.StringUtils;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;

/**
 * web页面
 * <p>
 * Created by han on 2019/06/12
 */
public class WebActivity extends BaseTranBarActivity implements OnNavgationBarClickListener {

    private final String STYLE_HEADER = "<!DOCTYPE html><html><head> <meta charset=\"UTF-8\" > <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\"> <style>p { max-width: 100%; word-break:break-all !important; } img { max-width: 100% !important;height: auto !important;}</style></head><body>";

    public static final int WEB_TYPE_DEFAULT = 0x00;//默认
    public static final int WEB_TYPE_PAY_AGREEMENT = 0x01;//支付协议
    public static final int WEB_TYPE_REGISTER_AGREEMENT = 0x02;//注册协议
    public static final int WEB_TYPE_ABOUT_US = 0x03;//关于我们
    public static final int WEB_TYPE_APPLY_MFRS_AREA = 0x04;//开设厂商专区
    public static final int WEB_TYPE_BIG_PURCHASE = 0x05;//大宗采购
    public static final int WEB_TYPE_INVOICE_KNOWS = 0x06;//发票须知

    //nav bar
    private NavigationBarLayout nav_bar_web;
    //web container
    private FrameLayout fl_webview;
    //加载进度条
    private ProgressBar proBar_web;
    //webview
    private WebView mWebView;

    private StringBuilder stringBuilder;

    //url
    private String mWebUrl;
    //详情id
    private String mId;
    //详情类型
    private int mWebType;

    @Override
    protected void initView() {
        nav_bar_web = findViewById(R.id.nav_bar_web);

        fl_webview = findViewById(R.id.fl_webview);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        initWebView();
        setWebData();
    }

    @Override
    protected void initListener() {
        nav_bar_web.setOnNavgationBarClickListener(this);
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_web;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {

    }

    //渲染数据
    private void setWebData() {
        Intent mIntent = getIntent();

        if (mIntent != null) {
            mWebType = mIntent.getIntExtra(Constants.KeyType, WEB_TYPE_DEFAULT);
            mId = mIntent.getStringExtra(Constants.KeyId);
            mWebUrl = mIntent.getStringExtra(Constants.KeyUrl);
        }

        switch (mWebType) {
            case WEB_TYPE_REGISTER_AGREEMENT://注册协议
                nav_bar_web.setNavBarTitle(R.string.text_register_agreement);
                getRegisterAndPayAgreement("0");
                break;
            case WEB_TYPE_PAY_AGREEMENT://支付协议
                nav_bar_web.setNavBarTitle(R.string.text_pay_agreement);
                getRegisterAndPayAgreement("1");
                break;
            case WEB_TYPE_ABOUT_US://关于我们
                nav_bar_web.setNavBarTitle(R.string.text_about_us);
                getSettingPageWeb("2");
                break;
            case WEB_TYPE_APPLY_MFRS_AREA://开设厂商专区
                nav_bar_web.setNavBarTitle(R.string.text_apply_open_manufacturer_area);
                getSettingPageWeb("0");
                break;
            case WEB_TYPE_BIG_PURCHASE://大宗采购
                nav_bar_web.setNavBarTitle(R.string.text_bulk_purchase);
                getSettingPageWeb("1");
                break;
            case WEB_TYPE_INVOICE_KNOWS://发票须知
                nav_bar_web.setNavBarTitle(R.string.text_notes_for_invoice);
                getInvoiceNotes();
                break;
            default:
                loadUrl();
                break;
        }
    }

    private void loadUrl() {
        if (mWebUrl == null) {
            return;
        }

        mWebView.loadUrl(mWebUrl);
    }

    private void getSettingPageWeb(@NonNull String type) {
        showLoadingDialog();

        UserApiIO.getInstance().getHtmlFromSettingPage(type, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                mWebView.loadDataWithBaseURL(HttpUrls.API_HOST, StringUtils.getNoNullString(res.getData()), "text/html", "utf-8", null);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //注册和支付协议
    private void getRegisterAndPayAgreement(@NonNull String type) {
        showLoadingDialog();

        CommonApiIO.getInstance().getRegisterAndPayAgreement(type, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                mWebView.loadDataWithBaseURL(HttpUrls.API_HOST, StringUtils.getNoNullString(res.getData()), "text/html", "utf-8", null);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //发票须知
    private void getInvoiceNotes() {
        showLoadingDialog();

        InvoiceApiIO.getInstance().getInvoiceNotes(new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                mWebView.loadDataWithBaseURL(HttpUrls.API_HOST, res.getData(), "text/html", "utf-8", null);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }


    //初始化webview
    private void initWebView() {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams paramsProgressBar = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 8);

        paramsProgressBar.gravity = Gravity.TOP;

        mWebView = new WebView(mContext);

        mWebView.setBackgroundColor(0);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setBlockNetworkImage(false);
        mWebView.getSettings().setDomStorageEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(mWebView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    proBar_web.setVisibility(View.GONE);
                } else {
                    proBar_web.setProgress(newProgress);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                return super.onJsAlert(view, url, message, result);
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (StringUtils.isHttp(url)) { //http和https协议开头的执行正常的流程
                    return false;
                }

                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

        proBar_web = new ProgressBar(mContext, null, android.R.attr.progressBarStyleHorizontal);

        proBar_web.setMax(100);
        proBar_web.setProgress(0);
        proBar_web.setProgressDrawable(ContextCompat.getDrawable(mContext, R.drawable.progress_web));

        fl_webview.addView(mWebView, params);
        fl_webview.addView(proBar_web, paramsProgressBar);
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.clearHistory();
            //webview.pauseTimers();
            mWebView.setWebChromeClient(null);
            mWebView.destroy();
            mWebView = null;
        }
        if (fl_webview != null) {
            fl_webview.removeAllViews();
            fl_webview = null;
        }
        super.onDestroy();
    }
}
